<template>
  <t-space direction="vertical" size="large">
    <t-checkbox v-model="autoUpload">自动上传</t-checkbox>
    <t-form id="form" @reset="onReset" @submit="onSubmit">
      <t-form-item> </t-form-item>
      <t-form-item label="姓名">
        <t-input name="name"></t-input>
      </t-form-item>
      <t-form-item label="密码">
        <t-input type="password" name="password" />
      </t-form-item>
      <t-form-item label="头像" name="thumb">
        <t-upload
          action="http://localhost:3000/api/upload"
          v-model="upload.files"
          theme="image"
          tips="请选择单张图片文件上传"
          accept="image/*"
          :auto-upload="autoUpload"
          :sizeLimit="500"
        ></t-upload>
      </t-form-item>

      <t-form-item>
        <t-space size="small">
          <t-button theme="primary" type="submit">提交</t-button>
          <t-button theme="default" variant="base" type="reset">重置</t-button>
        </t-space>
      </t-form-item>
      <t-form-item> </t-form-item>
    </t-form>
  </t-space>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import request from '../utils/request'
const autoUpload = ref(true)

const upload = reactive({ files: [] })
const onSubmit = async function ({ validateResult, firstError }) {
  //var form = document.forms.namedItem('form')
  var form = document.getElementById('form')
  const formData = new FormData(form)
  console.log(upload.files[0])
  if (autoUpload.value) formData.append('thumb', upload.files[0].response.response.url)
  else formData.append('thumb', upload.files[0].raw)

  if (validateResult === true) {
    request.sending('test', formData)
  } else {
    console.log('Errors: ', validateResult)
    MessagePlugin.warning(firstError)
  }
}
const onReset = () => {
  MessagePlugin.success('重置成功')
}

//@validate="onValidate"
//:size-limit="{ size: 1, unit: 'MB' }"
const onValidate = (params) => {
  const { files, type } = params
  console.log('onValidate', type, files)
  const messageMap = {
    FILE_OVER_SIZE_LIMIT: '文件大小超出限制，已自动过滤',
    FILES_OVER_LENGTH_LIMIT: '文件数量超出限制，仅上传未超出数量的文件',
    // if you need same name files, setting allowUploadDuplicateFile={true} please
    FILTER_FILE_SAME_NAME: '不允许上传同名文件',
    BEFORE_ALL_FILES_UPLOAD: 'beforeAllFilesUpload 方法拦截了文件',
    CUSTOM_BEFORE_UPLOAD: 'beforeUpload 方法拦截了文件'
  }
  // you can also set Upload.tips and Upload.status to show warning message.
  messageMap[type] && MessagePlugin.warning(messageMap[type])
}
//@success="success"
const success = (context) => {
  formData.value.thumb = context.response.response.url
}
//@fail="fail"
const fail = ({ file }) => {
  MessagePlugin.error(`文件 ${file.name} 上传失败`)
}
//:format-response="formatResponse"
const formatResponse = (response) => {
  return response.response.url
}
</script>
